﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sunny.Controls.Searcher
{
	public class SimpleSearcher : ControlList<SearchItem>
	{

		//private ControlList<SearchItem> _Items;
		//[System.Web.UI.PersistenceMode(System.Web.UI.PersistenceMode.InnerProperty)]
		//public ControlList<SearchItem> Items
		//{
		//	get
		//	{
		//		if (this._Items == null)
		//			this._Items = new ControlList<SearchItem>(this.ContentTemplateContainer.Controls);
		//		return this._Items;
		//	}
		//}

		public SimpleSearcher(System.Windows.Controls.UIElementCollection baseList):base(baseList)
		{

			//this.UpdateMode = System.Web.UI.UpdatePanelUpdateMode.Conditional;
			//this.SearchItems = items;
			//foreach (SearchItem item in items)
			//{
			//    item.SimpleSearcherLayout.Style["float"] = "left";
			//    item.SimpleSearcherLayout.Style["margin-left"] = "5px";a
			//    this.ContentTemplateContainer.Controls.Add(item.SimpleSearcherLayout);
			//}
		}

		//public SimpleSearcher(System.Collections.Generic.IEnumerable<SearchItem> items)
		//    : base(System.Web.UI.HtmlTextWriterTag.Div)
		//{
		//    this.SearchItems = items;
		//    foreach (SearchItem item in items)
		//    {
		//        item.SimpleSearcherLayout.Style["float"] = "left";
		//        item.SimpleSearcherLayout.Style["margin-left"] = "5px";
		//        this.Controls.Add(item.SimpleSearcherLayout);
		//    }
		//}

		public WhereCommand WhereCommand
		{
			get
			{
				SearchItem[] items = this.OfType<SearchItem>().ToArray();

				if (items.Length == 0)
					return null;
				WhereCommand whereCommand = new WhereCommand();
				for (int i = 0; i < items.Length; i++)
				{
					SearchItem searchItem = items[i];
					string commandText = null;

					foreach (string field in items.ElementAt(i).Fields)
					{
						WhereCommand command = searchItem.GetCommand(field, whereCommand.Parameters.Count());

						if (command == null)
							continue;
						if (commandText == null)
							commandText += "(";
						else commandText += "||";

						commandText += command.Text;
						whereCommand.Parameters = whereCommand.Parameters.Concat(command.Parameters).ToArray();
					}
					if (commandText != null)
					{
						if (whereCommand.Text != null)
							whereCommand.Text += "&&";
						whereCommand.Text += commandText + ")";
					}
				}
				if (whereCommand.Parameters.Length == 0)
					return null;
				return whereCommand;
			}
		}
	}
}